package site.https;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * @author haocongshun
 * @date 2023/03/30 15:59:30
 */
public class RuleGenerate {
    public static void main(String[] args) {
        String s = ResourceUtil.readUtf8Str("rule.txt");
        List<Item> items = Arrays.stream(s.split("\n"))
                .map(x -> x.trim().substring(1))
                .filter(StrUtil::isNotBlank)
                .map(Item::new)
                .filter(x -> !StrUtil.equalsIgnoreCase(x.action, "DIRECT"))
                .filter(x -> !StrUtil.equalsIgnoreCase(x.method, "IP-CIDR"))
                .collect(Collectors.toList());
        List<String> sqls = new LinkedList<>();
        for (int i = 0; i < items.size(); i++) {
            sqls.add(items.get(i).toSql(i + 1));
        }
        for (String sql : sqls) {
            System.out.println(sql);
        }
    }

    @Data
    @Accessors(chain = true)
    private static class Item {
        private String content;
        private String method;

        private String action;

        public Item(String s) {
            String[] split = s.split(",");
            method = split[0].trim();
            content = split[1].trim();
            action = split[2].trim();
        }

        public String toSql(long id) {
            String sql = """
                    MERGE INTO connection_rule (id, content, method, action) KEY (id) VALUES (%s, '%s', '%s', '%s');
                    """;
            method = switch (method) {
                case "DOMAIN-SUFFIX" -> "END_WITH";
                case "DOMAIN-KEYWORD" -> "CONTAINS";
                case "DOMAIN" -> "EQUALS";
                default -> throw new RuntimeException();
            };
            return String.format(sql, id, content, method, action.toUpperCase(Locale.ROOT));
        }
    }
}
